package com.hd.trans.extension

import com.hd.trans.network.ApiServiceManager
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.network.apiService.ApiException
import com.hd.trans.network.bean.DataResponse

suspend fun  <T : DataResponse> apiCall(retryWhenTimeError:Boolean = true, func:suspend ()->T)  : T {
    val result = func.invoke()
    sureDiffTime()
    return when(result.code){//11000 代表上传接口继续上传
        10000,11000-> result
        11108,11120->{//时间未同步错误
            //同步服务器时间
            sureDiffTime(true)
            if(retryWhenTimeError){
                return apiCall(false,func)
            }
            throw ApiException(result.code, result.requestUrl)

        }
        else -> throw ApiException(result.code, result.requestUrl)
    }
}

private suspend fun sureDiffTime(hardUpdate:Boolean = false) {
    val time = PreferenceMgr.getInstance().serverTimeStamp
    if(time == 0L || hardUpdate){
        val response = ApiServiceManager.universalService.getUTCTime()
        if(response.isResponseSuccess){
            PreferenceMgr.getInstance().saveServerTimeStamp(response.utctime * 1000)
        }
    }
}